<?php

namespace app\api\controller\baiying;

use app\common\controller\Api;
use app\common\exception\UploadException;
use think\Config;
use think\Hook;
use baiying\lib\BYGetTokenClient;

/**
 * 公共接口
 */
class Bybase extends Api {

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    
    protected $appkey = 'i3GUznDena3nJZBx';
    protected $appsecret = '3sXMd5NXrCeZ57lnfI9UMpPcu8Y5B2';
    public $companyId = '98920';
    
    public $access_token = null;

    public function _initialize() {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__'); //跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        $info = $this->getBaiyingToken();
        $this->access_token = $info['token']?:'';
        parent::_initialize();
    }
    
    public function getToken(){
        $result = $this->getBaiyingToken();
        $this->success('成功',$result);
    }



    public function getBaiyingToken() {
        $info = db('ec_token')->where('platform','baiying')->find();
        if($info && $info['access_token'] && $info['expire'] > time()){
            return ['status'=>2000,'token'=>$info['access_token']];
        }
        
        
        $token = new BYGetTokenClient($this->appkey, $this->appsecret);
        $grant_type = 'platform';
        $result = $token->get_token($grant_type, $this->companyId);
        if($result['code'] == 200 && $result['success']){
            db('ec_token')->where('platform','baiying')->update([
               'access_token'=> $result['data']['access_token'],
                'expire'=> $result['data']['expires_at'] / 1000,
                'config'=> json_encode($result,JSON_UNESCAPED_UNICODE),
                'updatetime'=>time()
            ]);
            return ['status'=>2000,'token'=>$result['data']['access_token']];
        }
        
        return ['status'=>4000,'msg'=>'获取失败'];

    }

}
